
package org.jeecg.modules.demo.student.service;

import io.minio.*;
import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
@Slf4j
public class MinIOService {

    @Autowired
    private MinioClient minioClient;

    //@Value("${minio.default-bucket}")
    private String defaultBucket = "uploads1";

    /**
     * 检查桶是否存在，不存在则创建
     */
    private void ensureBucketExists(String bucketName) throws MinioException, IOException, NoSuchAlgorithmException, InvalidKeyException {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            throw new RuntimeException("无法连接到MinIO服务，请检查MinIO配置或服务状态: " + e.getMessage(), e);
        }
    }

    /**
     * 上传文件到MinIO
     */
    public String uploadFile(MultipartFile file, String bucketName) {
        try {
            if (bucketName == null || bucketName.isEmpty()) {
                bucketName = defaultBucket;
            }

            ensureBucketExists(bucketName);

            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
            String objectName = UUID.randomUUID() + fileExtension;

            InputStream inputStream = file.getInputStream();
            String contentType = file.getContentType() != null ? file.getContentType() : "application/octet-stream";

            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(inputStream, file.getSize(), -1)
                    .contentType(contentType)
                    .build());

            return objectName;
        } catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        }
    }

    /**
     * 生成预签名URL
     */
    public String getPresignedUrl(String objectName, String bucketName, int expirySeconds) {
        try {
            if (bucketName == null || bucketName.isEmpty()) {
                log.info("存储桶为空" + bucketName);
                throw new IllegalArgumentException("请指定存储桶名称");
            }
            
            if (objectName == null || objectName.isEmpty()) {
                log.info("对象名为空");
                return null;
            }

            // 确保存储桶存在
            ensureBucketExists(bucketName);
            
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(io.minio.http.Method.GET)
                    .bucket(bucketName)
                    .object(objectName)
                    .expiry(expirySeconds)
                    .build());
        } catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException("生成预签名URL失败: " + e.getMessage(), e);
        }
    }
}